<template>
  <div>
    <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="返回" sub-title="文章编辑页面" @back="backToIndex" />
    <div class="main-body">
      <a-form :model="formState" v-bind="layout" :validate-messages="validateMessages" @finish="onFinish"
        :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item name="id" label="文章id">
          <a-input-number v-model:value="formState.id" :disabled="true" />
        </a-form-item>
        <a-form-item hasFeedback name="title" label="文章标题" :rules="[{ required: true, min: 1, whitespace: true }]">
          <a-input v-model:value="formState.title" />
        </a-form-item>
        <a-form-item name="category" label="文章类型">
          <a-radio-group v-model:value="formState.category" button-style="solid">
            <a-radio-button value="技术文章">技术文章</a-radio-button>
            <a-radio-button value="踩坑相关">踩坑相关</a-radio-button>
            <a-radio-button value="简单分享">简单分享</a-radio-button>
            <a-radio-button value="其他">其他</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="tags" label="标签">
          <a-input v-model:value="formState.tags" />
        </a-form-item>
        <a-form-item hasFeedback name="summary" label="文章简介" :rules="[{ required: true, min: 1, whitespace: true }]">
          <a-textarea v-model:value="formState.summary" />
        </a-form-item>
        <a-form-item name="文章详情" label="文章详情">
          <vue3-tinymce v-model="formState.content" :setting="setting" />
        </a-form-item>

        <a-form-item name="操作" label="文章操作">
          <a-space :size="60">
            <a-button type="primary" html-type="submit">{{isNew?"创建":"更新"}}</a-button>
            <a-button v-if="!isNew" type="danger" @click="handleDelete(formState.id)">删除</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router"
import { uploadImage } from "@/api/image"
import { oneArticle, saveArticle, deleteArticle } from "@/api/article"
import { message } from "ant-design-vue"
import Vue3Tinymce from '@jsdawn/vue3-tinymce';
export default {
  name: "ArticleManage",
  components: {
    Vue3Tinymce
  },
  setup() {
    let isNew = ref(true)
    const router = useRouter()
    const route = useRoute()
    let setting = reactive({
      menubar: false,
      toolbar: "code | undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
      toolbar_drawer: "sliding",
      quickbars_selection_toolbar: "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",
      plugins: "code link image media table lists fullscreen quickbars",
      language: 'zh_CN', //本地化设置
      language_url: 'https://lab.uxfeel.com/node_modules/tinymce/langs/zh_CN.js',
      images_upload_url: '/api/image/upload',
      //上传图片回调
      images_upload_handler: (blobInfo: any, success: any, failFun: any) => {
        let fd = new FormData()
        fd.append('file', blobInfo.blob())
        uploadImage(fd).then((res: any) => {
          console.log(res)
          success(res.data.imgUrl)
        }).catch((err: any) => {
          failFun("上传失败：" + err.message)
        })
      },
      height: 350
    })
    function backToIndex() {
      router.push('/index')
    }

    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };

    const validateMessages = {
      required: '${name} 不能为空'
    };

    let formState = ref({
      id: 0,
      title: "",
      summary: "",
      tags: "html,css",
      category: "技术文章",
      content: ""
    });

    onMounted(() => {
      if (route.query.id) {
        console.log("修改文章")
        oneArticle({ id: route.query.id }).then(res => {
          formState.value = res.data
          isNew.value = false
        }).catch(err => {
          message.error("获取失败，文章或许已删除")
          router.go(-1)
        })
      } else {
        console.log("新增文章")
      }
    })

    const onFinish = (values: any) => {
      saveArticle(formState.value).then((res: any) => {
        message.success(res.message)
        router.go(-1)
      })
    };

    function handleDelete(id: number) {
      deleteArticle({ id }).then((res:any) => {
        message.success(res.message)
        router.go(-1)
      })
    }

    return {
      isNew,
      setting,
      backToIndex,
      formState,
      onFinish,
      layout,
      validateMessages,
      labelCol: { style: { width: '150px' } },
      handleDelete
    };
  },
};
</script>

<style lang="less">
.main-body {
  padding: 20px 20% 20px 0;
  text-align: left;
}
</style>